<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 头部警告区域 -->
            <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable='false'>
            </el-alert>

            <!-- 选择 商品分类区域-->
            <el-row>
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择 商品分类 的级联选择框-->
                    <!-- options 数据源 -->
                    <el-cascader :props="cascaderProps" :options="cateList" v-model="selectedKeys"
                        @change="parenCateChanged" clearable :show-all-levels="true">
                    </el-cascader>
                </el-col>
            </el-row>

            <!-- tab 页签区 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 动态 -->
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数 按钮 -->
                    <el-button type='primary' size='mini' :disabled="isBtnDisableed" @click='addDialogVisible=true'>添加参数
                    </el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data='manyTabName' border stripe align='center'>
                        <!-- 展开行 -->
                        <el-table-column type='expand'>
                            <template slot-scope="scope">
                                <!-- 循环渲染tag 标签 -->
                                <el-tag closable @close='handleClose(index,scope.row)'
                                    v-for='(item,index) of scope.row.attr_vals' :key="index">{{item}}
                                </el-tag>
                                <!-- 动态编辑标签 输入文本框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type='index' label='#'></el-table-column>
                        <el-table-column label='参数名称' prop='attr_name'></el-table-column>
                        <el-table-column label='操作'>
                            <template scope='scope'>
                                <el-button size='mini' type="primary" icon="el-icon-edit"
                                    @click='showEditDialog(scope.row.attr_id)'>编辑</el-button>
                                <el-button size='mini' type="danger" icon="el-icon-delete"
                                    @click='removeParams(scope.row.attr_id)'>删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 静态 -->
                <el-tab-pane label="静态属性" name="only">
                    <!-- 添加属性 按钮 -->
                    <el-button type='primary' size='mini' :disabled="isBtnDisableed" @click='addDialogVisible=true'>添加属性
                    </el-button>
                    <!-- 添加属性表格 -->
                    <el-table :data='onlyTabName' border stripe align='center'>
                        <!-- 展开行 -->
                        <el-table-column type='expand'>
                            <template slot-scope="scope">
                                <!-- 循环渲染tag 标签 -->
                                <el-tag closable @close='handleClose(index,scope.row)'
                                    v-for='(item,index) of scope.row.attr_vals' :key="index">{{item}}
                                </el-tag>
                                <!-- 静态编辑标签 输入文本框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type='index' label='#'></el-table-column>
                        <el-table-column label='属性名称' prop='attr_name'></el-table-column>
                        <el-table-column label='操作'>
                            <template scope='scope'>
                                <el-button size='mini' type="primary" icon="el-icon-edit"
                                    @click='showEditDialog(scope.row.attr_id)'>编辑</el-button>
                                <el-button size='mini' type="danger" icon="el-icon-delete"
                                    @click='removeParams(scope.row.attr_id)'>删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数的对话框 -->
        <el-dialog :title=" '添加' + titleText " :visible.sync="addDialogVisible" width="50%" @close='addDialogClose'>
            <!-- 填写的表单 -->
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addFormRule" ref="addformRef">
                <el-row :gutter="20">
                    <el-form-item :label="titleText" prop='attr_name'>
                        <el-col :span="20">
                            <el-input v-model="addForm.attr_name"></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addPramas">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改按钮  的对话框 -->
        <el-dialog :title=" '修改' + titleText " :visible.sync="editDialogVisible" width="50%" @close='editDialogClose'>
            <!-- 填写的表单 -->
            <!-- 内容主体区域 -->
            <el-form :model="editForm" :rules="editFormRule" ref="editformRef">
                <el-row :gutter="20">
                    <el-form-item :label="titleText" prop='attr_name'>
                        <el-col :span="20">
                            <el-input v-model="editForm.attr_name"></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editPramas">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: 'params',
        data() {
            return {
                //商品分类 列表数据
                cateList: [],
                cascaderProps: {
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children',
                    expandTrigger: 'hover',
                },
                //双向绑定的数组
                selectedKeys: [],
                // 被激活的页签名称
                activeName: 'many',
                // 动态参数 数据存储
                manyTabName: [],
                // 静态属性 数据存储
                onlyTabName: [],

                // 控制添加对话框的显示和隐藏
                addDialogVisible: false,
                // 查询到的商品信息对象
                addForm: {
                    attr_name: ''
                },
                // 修改商品的校验规则
                addFormRule: {
                    attr_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' },
                    ]
                },

                // 控制编辑对话框的显示和隐藏
                editDialogVisible: false,
                // 修改的表单数据对象
                editForm: {},
                // 修改/编辑的校验规则
                editFormRule: {
                    attr_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' },
                    ]
                },
                // 控制按钮与文本框的切换显示     隐藏
                // inputVisible:false,
                //文本框中输入的内容    给每个数组中要单独定义
                // inputValue:''
            }
        },
        created() {
            this.getCateList()
        },
        methods: {
            // 获取所有的商品信息
            async getCateList() {
                const { data: res } = await this.$http.get('categories')
                // console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取商品信息失败！')
                }
                // 数据列表赋值
                this.cateList = res.data
                // console.log(this.cateList);
            },
            //级联选择框 变换时触发
            parenCateChanged() {
                // console.log(this.selectedKeys, 111);
                this.getParamsData()
            },
            //tab 页签 点击事件的处理函数
            handleTabClick() {
                // console.log(this.activeName);
                this.getParamsData()
            },
            //获取所有的数据
            async getParamsData() {
                //证明所选 不是三级
                if (this.selectedKeys.length !== 3) {
                    this.selectedKeys = []
                    this.manyTabName = []
                    this.onlyTabName = []
                    return
                }
                //根据所选分类的id 和当前所处的面板 获取对应的参数
                const { data: res } = await this.$http.get(`categories/${this.cateid}/attributes`, { params: { sel: this.activeName } })
                // console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取参数列表数据失败！')
                }
                // console.log(res.data);
                res.data.forEach(item => {
                    // console.log(item);
                    // 判断数组是否为空  空-false
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
                    // console.log(item.attr_vals);

                    //控制文本框的显示与隐藏
                    item.inputVisible = false
                    //文本框输入的值
                    item.inputValue = ''
                })
                console.log(res.data);

                if (this.activeName === 'many') {
                    this.manyTabName = res.data
                    // console.log(this.manyTabName,0);
                } else {
                    this.onlyTabName = res.data
                    // console.log(this.onlyTabName,11);

                }
            },
            //监听 添加动态参数/静态参数  对话框的关闭事件
            addDialogClose() {
                this.$refs.addformRef.resetFields()
            },
            //点击按钮  添加参数
            addPramas() {
                // 预校验
                this.$refs.addformRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.post(`categories/${this.cateid}/attributes`, {
                        attr_name: this.addForm.attr_name,
                        attr_sel: this.activeName
                    })
                    // console.log(res,101);
                    if (res.meta.status !== 201) {
                        return this.$message.error('添加分类失败！')
                    }
                    this.$message.success('添加分类成功！')
                    this.addDialogVisible = false
                    //刷新数据
                    this.getParamsData()
                })
            },
            //点击按钮 展示修改的对话框  
            //查询所有的参数/属性
            async showEditDialog(attr_id) {
                // console.log(attr_id);
                this.editDialogVisible = true
                const { data: res } = await this.$http.get(`categories/${this.cateid}/attributes/${attr_id}`, {
                    params: {
                        attr_sel: this.activeName
                    }
                })
                // console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取参数数据失败！')
                }
                ///////////////////////////////
                this.editForm = res.data
                // console.log(this.editForm);
            },
            //重置 修改/编辑的表单
            editDialogClose() {
                this.$refs.editformRef.resetFields()
            },
            //点击按钮 修改参数信息
            editPramas() {
                //接收校验的结果 valid
                this.$refs.editformRef.validate(async valid => {
                    // console.log(valid);
                    if (!valid) { // 校验不通过
                        // console.log(!valid);
                        return
                    }
                    // 可以发起修改用户的数据请求                                用户id         提交一个商品信息，
                    const { data: res } = await this.$http.put(`categories/${this.cateid}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
                    // console.log(res);
                    if (res.meta.status !== 200) {
                        this.$message.error('修改参数失败了！')
                    } else {
                        // 关闭修改的用户的对话框
                        this.editDialogVisible = false
                        // 重新获取用户列表数据--刷新数据
                        this.getParamsData()
                        // 提示修改成功
                        this.$message.success('修改参数成功！')
                    }
                })
            },
            //根据id 删除 参数数据
            removeParams(attrid) {
                this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async (suc) => {
                    const { data: res } = await this.$http.delete(`categories/${this.cateid}/attributes/${attrid}`)
                    // console.log(res);
                    if (res.meta.status !== 200) {
                        return this.$message.error('删除参数数据失败！')
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    // console.log(suc,12);
                    this.getParamsData()
                }).catch((err) => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                    // console.log(err);
                });
                // .catch(err => err);
                // 如果用户确认删除，则返回为字符串 confirm
                // 如果用户取消删除，则返回为字符串 cancel
                // console.log(res);
                // if (res !== 'confirm') {
                //     return this.$message.info('已经取消了删除！')
                // }
                // console.log('确认删除！');
            },

            // 文本框失去焦点/按下回车 触发
            handleInputConfirm(row) {
                console.log(row);
                // 输入的是不合法字符
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                }
                // 输入内容合法
                row.attr_vals.push(row.inputValue)
                row.inputValue = ''
                row.inputVisible = false
                // 发起网络请求  保存此次操作
                this.saveAttrVals(row)
            },

            // 点击按钮 将输入框 显示
            showInput(row) {
                row.inputVisible = true
                //文本框 自动获得焦点
                //$nextTick 方法的作用 就是当页面上的元素都被渲染完成之后 才会执行
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },

            async saveAttrVals(row) {
                console.log(row);
                // 发起网络请求  
                const { data: res } = await this.$http.put(`categories/${this.cateid}/attributes/${row.attr_id}`, {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(',')
                })
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('更新参数的数据失败！')
                }
                this.$message.success('更新参数成功了！')

            },
            // 循环渲染tag 标签删除 触发函数
            async handleClose(index, row) {
                row.attr_vals.splice(index, 1)
                this.saveAttrVals(row)
            }
        },
        computed: {
            // 如果按钮需要被禁用 则返回TRUE 否则返回false 
            isBtnDisableed() {
                if (this.selectedKeys.length !== 3) {
                    return true
                }
                return false
            },
            //  当前选中的三级分类的id
            cateid() {
                if (this.selectedKeys.length == 3) {
                    return this.selectedKeys[this.selectedKeys.length - 1]
                }
                return null
            },
            //动态计算标题的文本
            titleText() {
                if (this.activeName === 'many') {
                    return '动态参数'
                }
                return '静态参数'
            }
        }
    }
</script>

<style scoped>
    .el-row {
        margin: 15px 0;
    }

    .el-button {
        margin-bottom: 15px;
    }

    .el-tag {
        margin: 4px 15px;
    }

    .input-new-tag,
    el-input {
        margin: 6px;
        width: 150px;
    }
</style>